其他
漫画:星球入侵之策略模式
The following article is from JAVA小咖秀 Author 小小小咖
比基盗星球还有2万公里将要到达我星球入侵。。。
此时的why星球
public class SimpleHero {
public void fight (String condition) {
if (condition == null ) {
return;
}
if ("AgainstTheWind".equals(condition)) {
System.out.println("逆风翻盘策略");
} else if ("DownwindSuppression".equals(condition)) {
System.out.println("顺风压制策略");
} else if ("BalanceInPower".equals(condition)) {
System.out.println("势均力敌策略");
}
}
public static void main(String[] args) {
SimpleHero simpleHero = new SimpleHero();
simpleHero.fight("AgainstTheWind");
}
}
策略模式UML图:
public interface Strategy {
public void fight();
}
public class AgainstTheWindStrategy implements Strategy {
@Override
public void fight() {
System.out.println("逆风翻盘策略");
}
}
public class BalanceInPowerStrategy implements Strategy {
@Override
public void fight() {
System.out.println("势均力敌策略");
}
}
public class DownwindSuppressionStrategy implements Strategy {
@Override
public void fight() {
System.out.println("顺风压制策略");
}
}
public class Hero {
private Strategy strategy;
public Hero(Strategy strategy) {
this.strategy = strategy;
}
public void useStrategem() {
strategy.fight();
}
}
public class Battlegroud {
public static void main(String[] args) {
Hero hero = new Hero(new AgainstTheWindStrategy());
hero.useStrategem();
Hero hero1 = new Hero(new BalanceInPowerStrategy());
hero1.useStrategem();
Hero hero2 = new Hero(new DownwindSuppressionStrategy());
hero2.useStrategem();
}
}
tips :
策略模式优点:满足开闭原则,当新增策略时,只需要新增策略实现类,方便扩展,避免大量的if..else。
策略模式缺点:客户端需要知道所有的策略实现类,如果策略比较多的时候,类的数量也会比较多。
推荐阅读